package com.xs.langchain4j_springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xs.langchain4j_springboot.entity.ScheduleResult;
import com.xs.langchain4j_springboot.mapper.ScheduleResultMapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.model.output.structured.Description;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

import static com.xs.langchain4j_springboot.utils.StringUtil.appendIfNotEmpty;
import static com.xs.langchain4j_springboot.utils.StringUtil.appendWeatherInfo;
import static com.xs.langchain4j_springboot.utils.TimeUtil.formatDateTime;

@Slf4j
@Service
public class ToolsService {


    @Resource
    private ScheduleResultMapper matchMapper;



    @Tool("查询足球比赛详情")
    public String queryFootballMatchDetail(
            @P("时间格式必须是 yyyy-MM-dd")
            String matchTime,  // 将 Date 改为 String
            @P("球队")
            String teamName
    ) {
        QueryWrapper<ScheduleResult> queryWrapper = new QueryWrapper<>();

        // 添加时间条件（如果有）
        if (matchTime != null && !matchTime.isEmpty()) {
            queryWrapper.like("match_time", matchTime);
        }

        // 添加球队条件（如果有）
        if (teamName != null && !teamName.isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like("home_team_name_simplified", teamName)
                            .or()
                            .like("away_team_name_simplified", teamName)
            );

        }
        queryWrapper.last("limit 1");

        // 只查询一条记录
        Optional<ScheduleResult> scheduleResult = Optional.ofNullable(matchMapper.selectOne(queryWrapper));
        if (scheduleResult.isPresent()) {
            ScheduleResult matchInfo = scheduleResult.get();
            StringBuilder sb = new StringBuilder();
            // 基础比赛信息（直接来自matchInfo）
            sb.append("【比赛概况】\n");
            // appendIfNotEmpty(sb, "联赛ID：", matchInfo.getLeagueId());
            appendIfNotEmpty(sb, "联赛名称：", matchInfo.getLeagueNameSimplified());
            appendIfNotEmpty(sb, "赛季：", matchInfo.getSeason());
            appendIfNotEmpty(sb, "比赛轮次：", matchInfo.getRoundOrGroupName());
            appendIfNotEmpty(sb, "场地：", matchInfo.getMatchLocation());
            appendIfNotEmpty(sb, "比赛日期：", formatDateTime(matchInfo.getMatchTime()));
            appendWeatherInfo(sb, matchInfo.getTemperature(), matchInfo.getWeather());
            appendIfNotEmpty(sb, "主队：", matchInfo.getHomeTeamNameSimplified());
            appendIfNotEmpty(sb, "客队：", matchInfo.getAwayTeamNameSimplified());

            //log.info("比赛信息：{}", sb.toString());

            return "数据库查询结果\n" + sb.toString();

        }else {
            return "直接回复用户未找到该场比赛信息";
        }


    }




}